import request from '../../utils/request'
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageTo: ''
  },

  /**
   * 登录(授权按钮)
   */
  handleGetOpenId() {

    // 获取登录凭证
    wx.login({
      success: async(res) => {
        let code = res.code;
        let wechatUserVo = {
          avatarUrl: '',
          city: '',
          country: '',
          gender: '',
          language: '',
          nickName: '',
          province: '',
          code: ''
        };
        wx.getUserInfo({
          success: async(res) => {
            wechatUserVo = res.userInfo;
            wechatUserVo.code = code;
            // 将登录凭证发送服务器
            let result = await request('/auth/login', {
              wechatUserVo
            }, 'POST');
            let userInfo = this.data.userInfo;
            if (!userInfo) {
              wx.setStorageSync('userInfo', wechatUserVo);
              // 头部要带这个，所以设置缓存
              wx.setStorageSync('authorization', result.data);
              let userInfo = wx.getStorageSync('userInfo');
              let authorization = wx.getStorageSync('authorization');
              app.globalData.userInfo = userInfo;
              app.globalData.authorization = authorization;
            }
            wx.showToast({
              title: '授权登录成功！'
            })
            // 跳转页面
            if (this.data.pageTo == undefined || this.data.pageTo == '') {
              wx.navigateBack();
            } else {
              wx.redirectTo({
                url: this.data.pageTo
              });
            }

          }
        });

      }
    })
  },

  getUserInfo() {
    this.handleGetOpenId();
  },

  /**
   * 返回按钮
   */
  toBack() {
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.pageTo != undefined && options.pageTo != '') {
      this.setData({
        pageTo: options.pageTo
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})